package com.c611.smartclassroom.component;

import com.c611.smartclassroom.mapper.LogMapper;
import com.c611.smartclassroom.model.Log;
import com.c611.smartclassroom.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class LogHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<Object, Object> myRedisTemplate;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    LogMapper logMapper;

   private static Map<String,String> requestMap = new HashMap<>();

   public LogHandlerInterceptor() {
       //课表管理
       requestMap.put("exportSch","导出课表");
       requestMap.put("importSch","导入课表");

       //区域管理
       requestMap.put("addSchool","添加学校");
       requestMap.put("saveSchool","编辑学校");
       requestMap.put("delSchool","删除学校");
       requestMap.put("save","编辑教室");
       requestMap.put("defClassRoom","删除教室");
       requestMap.put("addZone","添加区域");
       requestMap.put("delZone","删除区域");
       requestMap.put("saveZone","添加区域");
       requestMap.put("addBuild","添加教学楼");
       requestMap.put("saveBuild","编辑教学楼");
       requestMap.put("delBuild","删除教学楼");
       requestMap.put("addClassRoom","添加教室");
       requestMap.put("setWeChat","设置微信");

       //系统设置
       requestMap.put("setCourseTime","设置课时");
       requestMap.put("setSemesterDate","设置学期");
       requestMap.put("editSemesterDate","编辑学期");
       requestMap.put("addRole","增加角色");
       requestMap.put("delRole","删除角色");
       requestMap.put("editAuth","编辑授权码");
       requestMap.put("delSemesterDate","删除学期");

       //工单管理模块
       requestMap.put("saveWorkOrderResult","处理工单");
       requestMap.put("delWorkOrder","删除工单");
       requestMap.put("addWorkOrder","增加工单");
       requestMap.put("addWorkOrder2","添加工单");


       //网关管理
       requestMap.put("addGateWay","添加网关");
       requestMap.put("saveGateWay","编辑网关");
       requestMap.put("delGateWay","删除网关");

       //设备管理
       requestMap.put("addDevice","添加设备");
       requestMap.put("saveDevice","编辑设备信息");
       requestMap.put("delDevice","删除设备");

       //用户管理
       requestMap.put("addUser","增加用户");
       requestMap.put("saveUser","编辑用户");
       requestMap.put("delUser","删除用户");
   }

    /*    private static final String USER_AGENT = "user-agent";
    private Logger logger = LoggerFactory.getLogger(this.getClass());*/

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println(myRedisTemplate.opsForValue().get("log") + "========================");
        Log newLog = (Log) myRedisTemplate.opsForValue().get("newLog");
        Object obj = myRedisTemplate.opsForValue().get("oldLog");
        if(obj != null && newLog != null) {
            //比较是否想等
            Log oldLog = (Log) obj;
            if(!oldLog.getOpermethod().equals(newLog.getOpermethod())) {
                logMapper.insertSelective(newLog);
                myRedisTemplate.opsForValue().set("oldLog",newLog);
            }

            if(!oldLog.getOperator().equals(newLog.getOperator())) {
                logMapper.insertSelective(newLog);
                myRedisTemplate.opsForValue().set("oldLog",newLog);
            }
        }

        if(obj == null && newLog != null) {
            logMapper.insertSelective(newLog);
            myRedisTemplate.opsForValue().set("oldLog",newLog);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        HttpSession sesson = request.getSession();
        User loginUser = (User) sesson.getAttribute("loginUser");

        if(loginUser == null) return false;

        String userName = "未知用户";
        if(loginUser.getUserrealname() != null)
            userName = loginUser.getUserrealname();

        String[] uri = request.getRequestURI().split("/");

        if(uri.length == 0) return false;

        String requestName = uri[uri.length - 1];
//        System.out.println(requestName);
        String chaineseName = requestMap.get(requestName);

//        System.out.println(chaineseName);

        if(chaineseName != null) {
            String ip = getIpAddr(request);
            Date requestTime = new Date();
            Log log = new Log();
            log.setOperator(userName);
            log.setOpdescribe(chaineseName);
            log.setOpermethod(requestName);
            log.setOpaddress(ip);
            log.setOpertime(requestTime);
            myRedisTemplate.opsForValue().set("newLog",log);
//            logMapper.insertSelective(log);
            return true;
        }

        return false;
    }


    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

}
